package com.weds.data_sync.launcher;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weds.data_sync.constant.ScriptServiceConstant;
import com.weds.data_sync.mapper.DataSyncAccountMapper;
import com.weds.data_sync.mapper.DataSyncScriptGroupMapper;
import com.weds.data_sync.pojo.entity.DataSyncAccountDO;
import com.weds.data_sync.pojo.entity.DataSyncScriptGroupDO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @Description 业务初始化器
 * @Author lihw
 * @Date 2024/1/4 13:39
 */
@Slf4j
@Component
public class BizInitRunner implements ApplicationRunner {

    @Autowired
    private DataSyncAccountMapper accountMapper;

    @Autowired
    private DataSyncScriptGroupMapper groupMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        accountInit();
        scriptGroupInit();
    }

    public void accountInit() {
        //  账户初始化
        Long count = accountMapper.selectCount(null);
        if (count <= 0) {
            log.info("开始初始化登录账户信息");
            DataSyncAccountDO accountDO = DataSyncAccountDO.builder()
                    .username("admin01")
                    .password(SecureUtil.md5("weds@123" + ScriptServiceConstant.COMMON_SECRET))
                    .build();
            int row = accountMapper.insert(accountDO);
            log.info("插入{}条账户信息: admin01/weds@123 ", row);
        }
    }

    /**
     * 脚本分组初始化
     */
    public void scriptGroupInit() {
        Long count = groupMapper.selectCount(new QueryWrapper<DataSyncScriptGroupDO>()
                .eq("is_default", 1)
                .eq("use_status_id", 1)
                .eq("is_delete", 0));
        if (count <= 0) {
            log.info("开始初始化默认脚本分组");
            DataSyncScriptGroupDO groupDO = DataSyncScriptGroupDO.builder()
                    .groupName("默认分组")
                    .isDefault(1)
                    .build();
            int row = groupMapper.insert(groupDO);
            log.info("插入{}条账户信息: 默认分组: {} ", row, groupDO);
        }
    }
}
